<template>
	<view class="container">
		<header>
			<view class='container-mineOrder-nav' @click="$goPath(1)">
				<image src='/static/images/right-white.png' mode='aspectFit|aspectFill|widthFix' alt="" />
				<view>商城订单</view>
			</view>

			<view class='orderList-tabs'>
				<view :class="[orderType == item.key ? 'tabs-item tabs-item-active' : 'tabs-item']" v-for="(item,index) in tabs"
					:key="index" @click="switchTabs(item.key)">
					{{ item.title }}
				</view>
			</view>
		</header>

		<section>
			<view class="sect-orderList" v-if="orderList.length > 0">
				<view class='orderList-item' v-for="(item,index) in orderList" :key="index" @click="goOrderDetails(item)">
					<view class='goods-items' v-for="goods in item.orderDetailList" :key="goods.productName">
						<view class='goods-items-img'>
							<image :src="goods.thumbnailUrl" mode='aspectFit|aspectFill|widthFix' alt="" />
						</view>
						<view class='goods-items-info'>
							<view class='goods-name'>{{ goods.productName }}</view>
							<view class='goods-item-price' v-if="!goods.limitation">
								<view>原价￥<text>{{ goods.showPrice }}</text>元</view>
								<view>共{{ goods.count }}件</view>
							</view>

							<view class='goods-item-price' v-else-if="goods.limitationBuyCount == 0">
								<view>限购价￥{{ goods.limitationPrice }}元</view>
								<view>共{{ goods.count - goods.limitationBuyCount }}件</view>
							</view>
							<view class='goods-price' v-else>
								<view class='goods-item-price' v-if="goods.count - goods.limitationBuyCount > 0">
									<view>限购价<text>{{ goods.limitationPrice }}</text>元</view>
									<view>共{{ goods.count - goods.limitationBuyCount }}件</view>
								</view>

								<view class='goods-item-price'>
									<view>原价￥{{ goods.showPrice }}元</view>
									<view>共{{ goods.limitationBuyCount }}件</view>
								</view>
							</view>

						</view>
					</view>

					<view class='orderList-item_toast'> {{ item.orderStatus }} </view>
					<view class='orderList-item_payment'>
						<text>兜兜卡￥{{ item.couponAmount }} 合计￥{{ item.totalPrice }}</text>
					</view>

					<view class='orderList-item_btns'>
						<view v-if="item.status == 0" @click.stop="onPayNow(item)">立即支付</view>
						<view v-if="item.status == 0" @click.stop="onCancelOrder(item)">取消订单</view>

						<view v-if="item.status == 1" @click.stop="onAgainOrder(item)">重新购买</view>

						<view v-if="item.status == 2 && item.logisticsStatus == 0" @click.stop="onLogistics()">催发货</view>

						<view v-if="item.status == 2 && item.logisticsStatus == 1" @click.stop="onConfirmTake(item)">确认收货</view>
						<view v-if="item.status == 2 && item.logisticsStatus == 1" @click.stop="goOrderDetails(item)">查看详情</view>

						<view v-if="item.status == 4" @click.stop="onAgainOrder(item)">再来一单</view>

						<view v-if="item.refundBtnStatus && item.status != 2" @click.stop="onOrderRefund(item)">申请退款</view>

						<view class='refund-btn' @click.stop="onRefundDetail(item)"
							v-if="item.status == 3 && item.refundStatus == 1">
							退款详情</view>
					</view>
				</view>

			</view>
			<view class="bill-empty" v-else>
				<image
					src="https://youpindou.com:8083/doudougou/image/showImg?imgUrl=/home/ddg_test/images/3b838297-ad51-4cab-b31d-0b9f568f7a6d.png"
					mode="aspectFit|aspectFill|widthFix"></image>
				<view>这里暂时什么都没有哦</view>
			</view>
		</section>

	</view>
</template>
<script>
	import {
		getUserInfo
	} from '@/common/auth';
	export default {
		data() {
			return {
				tabs: [{
						title: '全部',
						key: 'all'
					},
					{
						title: '待付款',
						key: 0
					},
					{
						title: '待发货',
						key: 1
					},
					{
						title: '已发货',
						key: 2
					},
					{
						title: '已完成',
						key: 3
					},
				],
				orderType: 'all',
				pageCurrent: 1,
				total: 0,
				orderList: [],
			}
		},
		onLoad(options) {
			this.orderType = options.orderType;
		},

		onShow() {
			this.getOrderList();
		},
		methods: {
			//获取订单列表
			async getOrderList() {
				let userInfo = getUserInfo()
				const {
					orderType,
					pageCurrent
				} = this;
				const param = {
					page: {
						current: pageCurrent,
						size: 20
					},
					query: {
						userId: userInfo.userId
					}
				};

				//待支付
				if (orderType == 0) {
					param.query.status = 0;
				}

				//待发货
				if (orderType == 1) {
					param.query.status = 2;
					param.query.logisticsStatus = 0;
				}

				//已发货
				if (orderType == 2) {
					param.query.status = 2;
					param.query.logisticsStatus = 1;
				}

				//已完成
				if (orderType == 3) {
					param.query.status = 4;
					param.query.logisticsStatus = 2;
				}

				if (this.orderList != this.total) {
					uni.showToast({
						title: '加载中',
						icon: 'loading'
					});
				}

				await this.$request.orderFindByPage(param).then(res => {
					if (res.code == 200 && res.isSuccess) {
						if (this.orderList != this.total) {
							uni.hideLoading();
						}

						const {
							records,
							total
						} = res.data;
						if (records.length > 0) {
							records.map(item => {
								if (item.status == 0) item.orderStatus = '订单即将关闭，建议尽快付款';
								if (item.status == 1) item.orderStatus = '订单已取消';
								if (item.status == 2 && item.logisticsStatus == 0) item.orderStatus = '商家还没有发货，请耐心等待';
								if (item.status == 2 && item.logisticsStatus == 1) item.orderStatus = '订单已发货，请注意查看物流';

								if (item.status == 2 && item.logisticsStatus == 3) item.orderStatus = '您的商品正在退货中';
								if (item.status == 3 && item.refundStatus == 1) item.orderStatus = '您的订单正在退货中';
								if (item.status == 3 && item.logisticsStatus == 4) item.orderStatus = '退货成功';
								if (item.status == 3 && item.logisticsStatus == 0 && item.refundStatus == 2) item.orderStatus =
									'退款成功';

								if (item.status == 4 && item.refundStatus == 2) item.orderStatus = '退货成功，订单已结束';
								if (item.status == 4 && item.refundStatus == 3) item.orderStatus = '退款失败';
								if (item.status == 4 && item.refundStatus == 4) item.orderStatus = '已取消退款';
								if (item.status == 4 && item.logisticsStatus == 2 && item.refundStatus == 0) item.orderStatus =
									'订单已完成';
								if (item.status == 4 && item.logisticsStatus == 2 && item.refundStatus == 0 && item
									.evaluateStatus != 0) item.orderStatus = '订单已完成';

								if (item.status == 4 && item.logisticsStatus == 2 && item.refundStatus == 0) {
									let nowDate = this.getData()
									const takedTime = item.takedTime?.replace(/-/g, "/");
									let time = this.dateDiff(nowDate, takedTime);
									if (time <= 7) {
										item.refundBtnStatus = true;
									}

								} else if (item.status == 2 && item.logisticsStatus == 1) {
									let nowDate = this.getData()
									const payTime = item.payTime?.replace(/-/g, "/");
									let time = this.dateDiff(nowDate, payTime);
									if (time <= 7) {
										item.refundBtnStatus = true;
									}
								}
							});

							if (pageCurrent > 1) {
								let list = _.uniqWith([...orderList, ...records], _.isEqual);
								this.orderList = list;
							} else {
								this.orderList = records;
							}
						}
						if (pageCurrent == 1 && records.length == 0) {
							this.orderList = [];
						}
						this.total = total;
					} else {
						uni.hideLoading();
					}
				});
			},
			getData() {
				// 创建一个 Date 对象
				var today = new Date();
				// 获取年、月、日、时、分、秒
				var year = today.getFullYear();
				var month = today.getMonth() + 1; // 月份是从 0 开始计数的，需要加1
				var day = today.getDate();
				var hours = today.getHours();
				var minutes = today.getMinutes();
				var seconds = today.getSeconds();

				// 格式化输出
				return year + "/" +
					(month < 10 ? "0" : "") + month + "/" +
					(day < 10 ? "0" : "") + day + " " +
					(hours < 10 ? "0" : "") + hours + ":" +
					(minutes < 10 ? "0" : "") + minutes + ":" +
					(seconds < 10 ? "0" : "") + seconds;
			},
			dateDiff(sDate1, sDate2) { //sDate1和sDate2是yyyy-MM-dd格式
				let aDate, oDate1, oDate2, iDays;
				aDate = sDate1.split("/");
				oDate1 = new Date(sDate1); //转换为yyyy-MM-dd格式
				aDate = sDate2?.split("/");
				oDate2 = new Date(sDate2);
				iDays = Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 / 24; //把相差的毫秒数转换为天数
				return iDays; //返回相差天数
			},

			//tab切换
			switchTabs(type) {
				this.orderType = type;
				this.pageCurrent = 1;
				this.getOrderList();
			},

			//跳转到订单详情
			goOrderDetails(values) {
				uni.navigateTo({
					url: `/pagesA/pocketShop/mine/orderDetail?orderId=${values.orderId}`
				});
			},

			//立即支付
			onPayNow(values) {
				uni.navigateTo({
					url: `/pagesA/pocketShop/mine/orderDetail?orderId=${values.orderId}`
				});
			},

			//查看物流 
			onLookLogistics(values) {
				values.orderDetailList.map(item => {
					item.logisticsCompany = values.logisticsCompany;
					item.logisticsNo = values.logisticsNo;
					item.logisticsStatusStr = values.logisticsStatus == 0 ? '未发货' : values.logisticsStatus == 1 ? '已发货' :
						values.logisticsStatus == 2 ? '已送达' : '';
				});
				uni.navigateTo({
					url: `/pagesA/pocketShop/mine/logisticsInfo?orderDetail=${encodeURIComponent(JSON.stringify(values))}`
				});
			},

			//催发货
			onLogistics() {
				uni.showToast({
					title: '已通知商家尽快发货',
					icon: 'success'
				});
			},

			//取消订单
			onCancelOrder(values) {
				uni.navigateTo({
					url: `/pagesA/pocketShop/mine/cancelReason?orderId=${values.orderId}`
				});
			},

			//申请退款
			onOrderRefund(values) {
				uni.navigateTo({
					url: `/pagesA/pocketShop/mine/orderRefund?orderDetail=${encodeURIComponent(JSON.stringify(values))}`
				});
			},

			//确认收货
			onConfirmTake(values) {
				this.$request.orderConfirmTake({
					orderId: values.orderId
				}).then(res => {
					if (res.code == 200 && res.isSuccess) {
						uni.showToast({
							title: '确认收货成功',
							icon: 'success'
						});
						this.getOrderList();
					}
				});
			},

			//再来一单
			onAgainOrder(values) {
				let productIdList = [];
				values?.orderDetailList.map(item => {
					productIdList.push(item.productId);
				})
				const param = {
					userId: values.userId,
					productIdList
				};
				this.$request.shoppingAdd(param).then(res => {
					if (res.code == 200 && res.isSuccess) {
						uni.showToast({
							title: '已加入到购物车',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: '加入购物车失败',
							icon: 'none'
						});
					}
				});
			},

			//退款详情
			onRefundDetail(values) {
				uni.navigateTo({
					url: `/pagesA/pocketShop/mine/refundDetails?orderDetail=${encodeURIComponent(JSON.stringify(values))}`
				});
			},

		},


		onReachBottom() {
			let {
				pageCurrent,
				total,
				orderList
			} = this;
			if (total > orderList.length) {
				pageCurrent++;
				this.pageCurrent = pageCurrent;
				this.getOrderList();
			} else {
				uni.showToast({
					title: '暂无更多',
					icon: 'none'
				});
			}
		}
	}
</script>
<style lang="scss" scoped>
	.container {
		width: 100%;
		min-height: 100vh;
		font-size: 28rpx;
		font-family: 'PingFang SC-Medium';
		background-color: #FED14E;
		display: flex;
		flex-direction: column;

		header {
			width: 100%;
			padding: 24rpx;
			padding-top: 100rpx;
			border-radius: 0 0 40rpx 40rpx;
			box-sizing: border-box;
			color: #fff;
			background-color: #32B499;
			background-image: url('https://youpindou.com/miniProgram/image/showImg?imgUrl=/home/ypd/images/homeTopIcon.png');
			background-size: 100% auto;
			background-repeat: no-repeat;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 100;

			.container-mineOrder-nav {
				display: flex;
				align-items: center;
				font-size: 36rpx;
				font-family: 'PingFang SC-Bold';
				margin-bottom: 24rpx;

				image {
					width: 16rpx;
					height: 28rpx;
					display: block;
					margin-right: 12rpx;
				}
			}

			.orderList-tabs {
				background-color: #F6F6F6;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 32rpx;

				.tabs-item {
					width: 160rpx;
					height: 60rpx;
					font-size: 28rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					font-weight: 500;
					color: #333;
				}

				.tabs-item-active {
					background: #32B499;
					border-radius: 32rpx;
					color: #FFFFFF !important;
					box-shadow: 0px 0px 4rpx 2rpx rgba(0, 0, 0, 0.12);
				}

			}

		}


		section {
			overflow: auto;
			padding-top: 270rpx;
			box-sizing: border-box;

			.sect-orderList {
				padding: 28rpx;
				padding-top: 0;
				padding-bottom: calc(env(safe-area-inset-bottom) + 14px);
				box-sizing: border-box;

				.orderList-item {
					background-color: #fff;
					border-radius: 20rpx;
					padding: 24rpx;
					box-sizing: border-box;
					margin-bottom: 24rpx;

					.goods-items {
						display: flex;
						align-items: flex-start;
						margin-bottom: 24rpx;

						.goods-items-img {
							width: 128rpx;
							height: 128rpx;

							image {
								width: 100%;
								height: 100%;
								display: block;
								border-radius: 8rpx;
							}
						}

						.goods-items-info {
							flex: 1;
							height: 128rpx;
							color: #333333;
							display: flex;
							flex-direction: column;
							justify-content: space-between;
							padding-left: 20rpx;
							box-sizing: border-box;

							.goods-name {
								display: -webkit-box;
								-webkit-box-orient: vertical;
								-webkit-line-clamp: 1;
								overflow: hidden;
								font-size: 28rpx;
								font-weight: bold;
								margin-bottom: 10rpx;
							}

							.goods-price {
								display: flex;
								align-items: center;
								justify-content: flex-start;

								text {
									font-family: 'DIN-Medium';
									font-size: 32rpx;
								}

								view:first-child {
									margin-right: 10rpx;
									color: #EA5F5F;
								}

								view:last-child {
									color: #999999;
									font-size: 24rpx;
								}


							}


						}
					}
				}

			}
		}

	}

	.bill-empty {
		width: 100%;
		min-height: 90vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28rpx;
		color: #999999;
		border-radius: 40rpx;

		image {
			width: 620rpx;
			height: 308rpx;
			display: block;
			margin-bottom: 24rpx;
		}
	}

	.orderList-item_toast {
		width: 100%;
		height: 36px;
		background: #F6F6F6;
		box-shadow: 1px 1px 1px 0px rgba(0, 0, 0, 0.01);
		border-radius: 8px;
		display: flex;
		align-items: center;
		font-family: 'PingFang SC-Medium';
		color: #32B499;
		padding-left: 12px;
		box-sizing: border-box;
	}

	.orderList-item_payment {
		font-size: 14px;
		text-align: right;
		margin-top: 12px;
	}

	.orderList-item_payment>span:last-child {
		color: #EA5F5F;
		font-size: 20px;
		font-family: 'DIN-Bold';
	}

	.orderList-item_btns {
		display: flex;
		flex-direction: row-reverse;
		align-items: center;
		justify-content: flex-start;
		margin-top: 12px;
	}

	.orderList-item_btns>view {
		width: 93px;
		height: 28px;
		background: #F6F6F6;
		border-radius: 15px 15px 15px 15px;
		font-size: 14px;
		font-family: 'PingFang SC-Medium';
		font-weight: 500;
		color: #333333;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-left: 12px;
	}

	.orderList-item_btns>view:first-child {
		background-color: #32B499;
		color: #fff;
	}
</style>